import axios, {AxiosInstance, AxiosRequestConfig} from 'axios'
import {getCertainPrincipal} from "./auth.util.tsx";
import {url} from '../assets/settings.json'

export const URL = url;
const BASE_URL = '/api'

type URL = {
    remark?: string,
    url: string
    method: string
    headers?: Record<string, string>,
    anonymous: boolean
}

const proxy: AxiosInstance = axios.create({
    timeout: 10000,
})

export function send(url: URL, payload?: any, pathVariable?: string[]) {
    let urlString = url.url
    if (pathVariable) {
        urlString = urlString + '/' + pathVariable.join('/')
    }

    const config: AxiosRequestConfig = {
        url: urlString,
        baseURL: BASE_URL,
        method: url.method,
        headers: url.headers,
    }

    // ~ 处理非 "匿名" 请求
    if (!url.anonymous) {
        if (config.headers == undefined) {
            config.headers = {}
        }
        config.headers['access-token'] = getCertainPrincipal().token
    }

    if (config.method === 'GET') {
        config.params = payload
    } else {
        config.data = payload
    }

    return proxy(config)
}
